import React, { useEffect, useState, useRef } from 'react'
import { useModel, history, useSearchParams } from '@umijs/max'
import { Form, Select, Space, Button, Checkbox, Divider, Input, InputNumber, Radio, Card } from 'antd'
import styles from './index.less'
// import './index.less'

export default props => {
  const { value, onChange, formRef, sellPlan, disabled, sellTermList } = props
  const { SetSell } = useModel('Goods')
  const [sellData, setSellData] = useState([])
  const triggerChange = useRef(false)

  useEffect(() => {
    if (value && value.length) {
      setSellData(value)
    }
  }, [])

  useEffect(() => {
    if (triggerChange.current) {
      if (sellData && sellData.length) {
        onChange(sellData)
      } else {
        onChange(null)
      }
    } else {
      triggerChange.current = true
    }
    SetSell(sellData.filter(i => i.checked).sort((a, b) => a.id - b.id))
  }, [sellData])

  const onPlanCheck = target => {
    const { checked, value } = target
    let hasItem = false
    let newList = []
    newList = sellData.map(item => {
      if (item.id === value) {
        item.checked = checked
        hasItem = true
      }
      return item
    })

    if (!hasItem) {
      const sellPlanItem = sellPlan.filter(item => item.id === value)[0]
      const canBuyOutValue = 1
      const packKey = `sell_package_name__${value}`
      const packname = formRef.getFieldValue(packKey)
      newList = [
        ...sellData,
        {
          id: value,
          checked,
          support_fixed_price: canBuyOutValue,
          package_name: sellPlanItem.show_name,
          type: sellPlanItem.type
        }
      ]
      formRef.setFieldValue(`support_fixed_price_${value}`, canBuyOutValue)
      if (!packname) {
        formRef.setFieldValue(packKey, sellPlanItem.show_name)
      }
    }
    setSellData(newList)
  }

  const handleChangeBuyOut = (e, id) => {
    const newData = sellData.map(item => {
      if (item.id === id) {
        item.support_fixed_price = e
      }
      return item
    })
    setSellData(newData)
  }

  const handleChangeSellName = (e, id) => {
    const newData = sellData.map(item => {
      if (item.id === id) {
        item.sell_package_name_ = e
      }
      return item
    })
    setSellData(newData)
  }

  const handleChangeSellInfo = (e, id, key) => {
    const newData = sellData.map(item => {
      if (item.id === id) {
        item[key] = e
      }
      return item
    })
    setSellData(newData)
  }

  const handleChangeSellPeriod = (e, id) => {
    const newData = sellData.map(item => {
      if (item.id === id) {
        const rentPeriod = sellPlan.find(i => i.id === id)?.rent_period
        if (rentPeriod) {
          const data = e.sort((a, b) => a - b).map(i => rentPeriod.find(it => it.id === i))
          item.rent_period_ids = data
          item.rent_period = data
        }
      }
      return item
    })
    setSellData(newData)
  }

  return (
    <Card>
      <Space direction='vertical'>
        {sellPlan.map(({ id, show_name, description, rent_period }) => {
          const cursellData = sellData.filter(item => item.id === id || item.rent_plan_id === id)?.[0] || {}
          const checked = cursellData.checked
          return (
            <div key={id}>
              <Checkbox
                onChange={e => onPlanCheck(e.target)}
                checked={checked}
                disabled={disabled}
                value={id}
                style={{ marginBottom: checked ? '20px' : '0' }}
              >{`${show_name}（${description}）`}</Checkbox>
              {checked ? (
                <Card>
                  <Form.Item
                    name={`support_fixed_price_${id}`}
                    key={id}
                    label='是否支持一口价'
                    rules={[{ required: true, message: '请设置是否支持一口价!' }]}
                  >
                    <Radio.Group onChange={e => handleChangeBuyOut(e.target.value, id)} disabled={disabled}>
                      <Radio value={1}>是</Radio>
                      <Radio value={0}>否</Radio>
                    </Radio.Group>
                  </Form.Item>
                  <Form.Item
                    name={`sell_package_name__${id}`}
                    help='修改名称后将替换该商品的买卖套餐名称'
                    label='套餐名称'
                  >
                    <Input disabled={disabled} onChange={e => handleChangeSellName(e.target.value, id)} />
                  </Form.Item>
                  <Form.Item
                    label='首付比例'
                    name={`first_price-${id}`}
                    rules={[{ required: true, message: '请设置首付比例!' }]}
                  >
                    <InputNumber
                      precision={0}
                      addonAfter={'%'}
                      max={100}
                      min={0}
                      className={styles.input_number_item}
                      bordered={false}
                      disabled={disabled}
                      onChange={e => handleChangeSellInfo(e, id, 'first_pay_ratio')}
                    />
                  </Form.Item>
                  <Form.Item
                    label='尾款期数'
                    name={`periods_amount-${id}`}
                    rules={[{ required: true, message: '请设置尾款期数!' }]}
                  >
                    <Select
                      disabled={disabled}
                      options={sellTermList}
                      onChange={e => handleChangeSellInfo(e, id, 'terms')}
                    />
                  </Form.Item>
                  <Form.Item
                    name={`sell_period_${id}`}
                    label='剩余尾款周期'
                    rules={[{ required: true, message: '请设置剩余尾款周期!' }]}
                    help='支付商品剩余所有尾款的总时间'
                  >
                    <Select
                      options={rent_period.map(({ id, rent_period }) => ({
                        label: rent_period,
                        value: id
                      }))}
                      mode='multiple'
                      disabled={disabled}
                      style={{ width: '100%' }}
                      onChange={e => handleChangeSellPeriod(e, id)}
                      placeholder='请选择尾款周期'
                    />
                  </Form.Item>
                </Card>
              ) : null}
            </div>
          )
        })}
      </Space>
    </Card>
  )
}
